package com.sgcc.dlsc.monitorredis.util;



import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by byddong on 2018/1/5.
 */
public class CommandProcess {
    private static final Logger LOGGER = Logger.getLogger(CommandProcess.class.getName());

    private static List<String> lcommand = new ArrayList<String>();

    private static ProcessBuilder processBuilder = new ProcessBuilder();

    public static void asyncExec(String command) throws IOException {
        lcommand.clear();
        String[] commandSplit = command.split(" ");
        for (int i = 0; i < commandSplit.length; i++) {
            lcommand.add(commandSplit[i]);
        }

        processBuilder.command(lcommand);
        processBuilder.redirectErrorStream(true);

        processBuilder.start();
    }

    public static String syncExec(List<String> command) throws Exception {
        processBuilder.command(command);
        processBuilder.redirectErrorStream(true);
        Process p = processBuilder.start();
        InputStream is = p.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader bs = new BufferedReader(inputStreamReader);
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (p.exitValue() != 0) {
//                说明命令执行失败
//                可以进入到错误处理步骤中
                throw new Exception("\n\n命令执行失败\ncommand : \n" + command.toString());

            }
            String line = null;
            String result = "";
            try {
                while ((line = bs.readLine()) != null) {
                    result += line+"\n";
                }
                result=result.substring(0,result.length()-1);
            } catch (IOException e) {
                LOGGER.error(e);
            } finally {
                inputStreamReader.close();
                bs.close();
                processBuilder.directory();
                return result;
            }
        }
    }

    public static String syncExec(String command) throws Exception {
        lcommand.clear();
        String[] commandSplit = command.split(" ");
        for (int i = 0; i < commandSplit.length; i++) {
            lcommand.add(commandSplit[i]);
            LOGGER.debug("[ " + i + " ] " +commandSplit[i]);
        }
        return syncExec(lcommand);
    }
}
